<extend name="layout/edit" />

<block name="HEADER">

</block>

<block name="CONTENT">
    <control:form id="form" />
</block>

<block name="FOOTER">
   <script type="text/javascript">
    var  page=(function(ns){
    	
    	//名称模板
	    ns.nameTemplet= function(e){

	    	
	    }
     	
		ns.init = function(){

		}
		

		//设置是否可以编辑
		ns.setReadonly =function(){
			if( form.getValue('give_type') == 1){
				form.setReadonly("freight_id",true,true);
			}else{
				form.setReadonly("freight_id",false,false);
				form.setValue("freight_id",'');
			}
		}
		
		//获取总库存
		ns.getTotalStock = function(){
			var totalStock = eval($.map(form.$grids['specsGrid'].getRows(),function(h){
				return h.stock || 0;
			}).join('+'));
			form.setValue('stocks', totalStock.toFixed(0) );
		}



		//商品选择规格
		ns.selectSpecs = function(){
			var selectedRow = form.$grids['setmealGrid'].getSelectedRows()[0];
			if(!selectedRow) return $.toast(0,"请先选择商品!");
	        var filter = {
	            url:"modules/common/selectGoodsSpecs",
	            mode:1,
	            goods_id:selectedRow.goods_id
	        }
	        $.openIframe(filter,"选择商品规格",['600px', '480px']);
		}
    	ns.selectSpecsCallback = function(ids,data){
    		var selectedRow = form.$grids['setmealGrid'].getSelectedRows()[0];
    		form.$grids['setmealGrid'].update(selectedRow.LAY_TABLE_INDEX,{
    			'specs_name': data[0]['name'],
    			'specs_id': data[0]['id'],
    			'sale_price': data[0]['sale_price'],
    		});
    	}
		

        //保存
        ns.save=function(){
        	var param = form.getData();
        	if(!param) return false;

        	var specsData = form.$grids['specsSetGrid'].getRows();
            //判断抢购开始时间不能大于抢购结束时间
            if(form.getValue('benefit_start_at')>form.getValue('benefit_end_at')){
                $.toast(0,'开始时间不能大于结束时间！');
                return;
            }

            for(var i in specsData){
            //抢购库存不能大于所在店铺下的规格库存
                if(specsData[i]['benefit_stock']>specsData[i]['stock']){
                    $.toast(0,'抢购库存不能大于现有库存！');
                    return;
                }
                if(Number(specsData[i]['sale_price'])<Number(specsData[i]['benefit_sale_price'])){
                    $.toast(0,'抢购价格不能大于销售价格！');
                    return;
                }
            }

        	form.save(4).then(function(res){
        		$.ajaxs('/admin/v1/goods/addGoodSpecs',{
        			goods_id:res.data,
	        		specsData: JSON.stringify($.map(specsData,function(h){
	        			h.goods_id = res.data;
	        			return h;
	        		})),
	        	}).then(function(res){
					form.opener.grid.load();
					$.close();
	    		});
        	});
        }
        return ns;
    }({}));
    
    $(function(){ page.init(); });
   </script>
</block>



